<?php

class net_mode3_news_newsModel extends FoundryModel
{
	protected $hasOne = array(
		'status',
	);

	protected $hasManyBelongsToMany = array(
		'tags',
	);
	/**
	 * init()
	 *
	 * init() is called in place of the __construct() method used by the
	 * FoundryModel super class
	 * This function will be called immediately after the __construct method
	 *
	 */ 
	public function init()
	{
	
	}

	public function findByTag()
	{
		
		$names = func_get_args();
		$mTag = FoundryController::model( 'tag' );
		$tag = $mTag->find( '*name = :n', array( ':n' => $names[0] ) );

		if( $tag[0]->uid ) {

			$sql = 'select ';
			foreach( $this->schema as $col => $filter ) {
				$sql .= $this->table.'.'.$col.', ';
			}
			$sql = substr( $sql, 0, strlen( $sql ) - 2 ).' from '.$this->table.
				' left join '.$this->nameSpace.'tagsMap on '.
				$this->table.'.uid = '.$this->nameSpace.
				'tagsMap.net_mode3_news_new_id where '.$this->nameSpace.
				'tagsMap.tag_id = '.$tag[0]->uid;
				
				
//			echo $sql;
			$stmt = $this->dbh->prepare( $sql );
			
			foreach( $names as $name ) {
				$stmt->bindParam( ':'.$name, $name );
			}
			
			$stmt->execute();
	
			$class = get_class( $this );		
	
			$all = $stmt->fetchAll();
			$this->callCallback( 'afterFind', &$all );
	
			$data = array();
			foreach( $all as $row ) {
				$temp = new $class();
				$temp->isNew = false;
				foreach( $row as $col => $val ) {
					$temp->$col = $val;
				}
				$data[] = $temp;
			}

		}


		return $data;
	}
	
	public function comments( $published = false )
	{
		$mComment = FoundryController::model( 'net.mode3.news:comment' );
		if( $published == false ) {
			$data = $mComment->find( 'and net_mode3_news_comment.net_mode3_news_new_id = '.
				$this->uid );
		} else {
			$data = $mComment->find( '*published = 1 and net_mode3_news_comment.net_mode3_news_new_id = '.
				$this->uid );
		
		}
					
		$this->comments = $data;
		return $data;
	}

}

?>